/**
 * 
 */
package org.dragonfire.editor.z80.hiliteRules;

import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;

/**
 * @author Darth Android
 * @date Oct 2, 2007
 */
public class SimplePatternRule implements IRule {

	IToken myToken;
	private String chars;
	private char end;
	private char start;
	private int startCol;
	private int endCol;

	public SimplePatternRule(char start, String chars, char end, IToken token, int startCol, int endCol) {
		Assert.isTrue(chars != null && token != null);
		this.endCol = endCol;
		this.startCol = startCol;
		this.start = start;
		this.end = end;
		this.chars = chars;
		myToken = token;
	}

	public IToken evaluate(ICharacterScanner scanner) {
		if (!(startCol > 0 && startCol <= scanner.getColumn()) && !(endCol > 0 && scanner.getColumn() <= endCol))
			return Token.UNDEFINED;
		char c = (char) scanner.read();
		if (c == start && start > 0)
			return evaluate(scanner, true);
		if (chars.contains(c + "") && end > 0)
			return evaluate(scanner, false);
		scanner.unread();
		return Token.UNDEFINED;
	}

	public IToken evaluate(ICharacterScanner scanner, boolean frontMatched) {
		char c = (char) scanner.read();
		if (!frontMatched && c == end)
			return myToken;
		if (chars.contains(c + ""))
			return evaluate(scanner, frontMatched);
		scanner.unread();
		if (frontMatched) {
			return myToken;
		}
		return Token.UNDEFINED;
	}
}
